import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import '../../../data/models/download_record.dart';
import 'dart:async';
import 'dart:io';

/// Android平台专用视频播放器（使用video_player）
class VideoPlayerDialogAndroid extends StatefulWidget {
  final DownloadRecord record;

  const VideoPlayerDialogAndroid({super.key, required this.record});

  @override
  State<VideoPlayerDialogAndroid> createState() =>
      _VideoPlayerDialogAndroidState();
}

class _VideoPlayerDialogAndroidState extends State<VideoPlayerDialogAndroid>
    with WidgetsBindingObserver {
  VideoPlayerController? _controller;
  bool _isLoading = true;
  bool _isFullScreen = false;
  bool _showControls = true;
  String? _errorMessage;
  Timer? _hideControlsTimer;
  Timer? _positionUpdateTimer;

  Duration _position = Duration.zero;
  Duration _duration = Duration.zero;
  bool _isPlaying = false;
  bool _isDragging = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initializeVideoPlayer();
    _startHideControlsTimer();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    _hideControlsTimer?.cancel();
    _positionUpdateTimer?.cancel();
    _controller?.removeListener(_onVideoPlayerChanged);
    _controller?.dispose();

    // 确保退出时恢复到竖屏模式
    _restorePortraitMode();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用重新获得焦点时，如果不在全屏状态，确保恢复到竖屏模式
    if (state == AppLifecycleState.resumed && !_isFullScreen) {
      _restorePortraitMode();
    }
  }

  /// 恢复到竖屏模式
  void _restorePortraitMode() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: SystemUiOverlay.values,
    );
  }

  /// 进入横屏全屏模式
  void _enterFullScreenMode() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  }

  /// 切换全屏
  void _toggleFullScreen() {
    setState(() {
      _isFullScreen = !_isFullScreen;
    });

    if (_isFullScreen) {
      _enterFullScreenMode();
    } else {
      _restorePortraitMode();
    }

    _showControlsTemporarily();
  }

  /// 显示控制栏（临时）
  void _showControlsTemporarily() {
    setState(() {
      _showControls = true;
    });
    _startHideControlsTimer();
  }

  /// 开始隐藏控制栏定时器
  void _startHideControlsTimer() {
    _hideControlsTimer?.cancel();
    _hideControlsTimer = Timer(const Duration(seconds: 3), () {
      if (mounted && !_isDragging) {
        setState(() {
          _showControls = false;
        });
      }
    });
  }

  /// 格式化时间
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    if (hours > 0) {
      return '${twoDigits(hours)}:${twoDigits(minutes)}:${twoDigits(seconds)}';
    } else {
      return '${twoDigits(minutes)}:${twoDigits(seconds)}';
    }
  }

  /// 初始化视频播放器（使用video_player）
  Future<void> _initializeVideoPlayer() async {
    try {
      print('🎬 开始初始化video_player视频播放器（Android）...');
      print('📁 文件路径: ${widget.record.localPath}');

      if (widget.record.localPath == null ||
          widget.record.localPath!.isEmpty) {
        print('❌ 本地文件路径为空');
        BotToast.showText(text: '本地文件路径为空');
        setState(() {
          _isLoading = false;
          _errorMessage = '本地文件路径为空';
        });
        return;
      }

      final file = File(widget.record.localPath!);
      if (!await file.exists()) {
        print('❌ 本地文件不存在: ${widget.record.localPath}');
        BotToast.showText(text: '本地文件不存在');
        setState(() {
          _isLoading = false;
          _errorMessage = '本地文件不存在';
        });
        return;
      }

      print('📊 文件存在，开始打开视频文件...');
      final fileSize = await file.length();
      print('  文件大小: $fileSize bytes');

      // 检查文件大小是否合理
      if (fileSize == 0) {
        throw Exception('视频文件为空');
      }

      // 创建VideoPlayerController
      _controller = VideoPlayerController.file(file);

      // 添加监听器
      _controller!.addListener(_onVideoPlayerChanged);

      // 初始化播放器，设置超时
      print('⏳ 正在初始化播放器...');
      await _controller!.initialize().timeout(
            const Duration(seconds: 15),
            onTimeout: () {
              throw Exception('视频文件打开超时，可能是文件损坏或格式不支持');
            },
          );

      // 检查播放器状态
      if (!_controller!.value.isInitialized) {
        throw Exception('播放器初始化失败');
      }

      print('✅ video_player视频播放器初始化成功');
      print('📊 视频信息:');
      print('  分辨率: ${_controller!.value.size}');
      print('  时长: ${_controller!.value.duration}');
      print('  是否循环: ${_controller!.value.isLooping}');

      // 更新状态
      if (mounted) {
        setState(() {
          _isLoading = false;
          _duration = _controller!.value.duration;
          _position = _controller!.value.position;
          _isPlaying = _controller!.value.isPlaying;
        });

        // 自动播放
        await _controller!.play();

        // 定期更新播放位置（video_player不会自动触发位置更新）
        _startPositionUpdateTimer();
      }
    } catch (e) {
      print('❌ video_player视频播放器初始化失败: $e');
      final friendlyError = _parseError(e.toString());
      BotToast.showText(text: '视频加载失败: $friendlyError');
      setState(() {
        _isLoading = false;
        _errorMessage = friendlyError;
      });
    }
  }

  /// 开始位置更新定时器（video_player需要手动更新位置）
  void _startPositionUpdateTimer() {
    _positionUpdateTimer?.cancel();
    _positionUpdateTimer = Timer.periodic(const Duration(milliseconds: 200), (timer) {
      if (!mounted || _controller == null || !_controller!.value.isInitialized) {
        timer.cancel();
        return;
      }

      if (!_isDragging) {
        setState(() {
          _position = _controller!.value.position;
        });
      }
    });
  }

  /// 视频播放器状态变化监听
  void _onVideoPlayerChanged() {
    if (!mounted || _controller == null) return;

    final value = _controller!.value;

    setState(() {
      _isPlaying = value.isPlaying;
      _duration = value.duration;
      // 注意：position 通过定时器更新，避免频繁更新

      // 如果有错误，显示错误信息
      if (value.hasError) {
        _errorMessage = _parseError(value.errorDescription ?? '未知错误');
        _isLoading = false;
        _positionUpdateTimer?.cancel();
      }

      // 如果初始化完成，停止加载
      if (value.isInitialized && _isLoading) {
        _isLoading = false;
      }
    });
  }

  /// 解析错误信息，提供更友好的错误提示
  String _parseError(String error) {
    final errorLower = error.toLowerCase();

    // 解码相关错误
    if (errorLower.contains('codec') ||
        errorLower.contains('decode') ||
        errorLower.contains('decoder') ||
        errorLower.contains('h264') ||
        errorLower.contains('h265') ||
        errorLower.contains('hevc')) {
      return '视频解码失败，可能是编码格式不支持。请尝试使用其他设备播放或联系技术支持';
    }

    // 文件相关错误
    if (errorLower.contains('file') ||
        errorLower.contains('not found') ||
        errorLower.contains('不存在') ||
        errorLower.contains('empty')) {
      return '视频文件不存在或已损坏';
    }

    // 超时错误
    if (errorLower.contains('timeout') || errorLower.contains('超时')) {
      return '视频加载超时，请检查文件是否完整';
    }

    // 权限错误
    if (errorLower.contains('permission') || errorLower.contains('权限')) {
      return '没有读取视频文件的权限，请在设置中授予存储权限';
    }

    // 格式错误
    if (errorLower.contains('format') || errorLower.contains('格式')) {
      return '视频格式不支持，请确认文件格式是否正确';
    }

    // 默认错误
    return '视频播放失败: ${error.length > 50 ? error.substring(0, 50) + "..." : error}';
  }

  /// 切换播放/暂停
  void _togglePlayPause() {
    if (_controller == null) return;

    if (_isPlaying) {
      _controller!.pause();
    } else {
      _controller!.play();
    }
    _showControlsTemporarily();
  }

  /// 跳转到指定位置
  void _seekTo(Duration position) {
    if (_controller == null) return;
    _controller!.seekTo(position);
    _showControlsTemporarily();
  }

  /// 关闭对话框
  void _closeDialog() {
    _controller?.pause();
    // 确保关闭时恢复到竖屏模式
    _restorePortraitMode();
    Get.back();

    // 延迟再次恢复竖屏模式，确保UI正确恢复
    Future.delayed(const Duration(milliseconds: 100), () {
      _restorePortraitMode();
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isFullScreen) {
      // 全屏模式：使用整个屏幕（包括安全区）
      return Scaffold(
        backgroundColor: Colors.black,
        body: SafeArea(
          top: false,
          bottom: false,
          left: false,
          right: false,
          child: _buildVideoContent(),
        ),
      );
    } else {
      // 普通模式：对话框
      return Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: EdgeInsets.zero,
        child: Container(
          width: Get.width * 0.85,
          height: Get.height * 0.6,
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: _buildVideoContent(),
        ),
      );
    }
  }

  /// 构建视频内容
  Widget _buildVideoContent() {
    return Stack(
      fit: _isFullScreen ? StackFit.expand : StackFit.loose,
      alignment: Alignment.center,
      children: [
        // 视频播放区域
        GestureDetector(
          onTap: () {
            setState(() {
              _showControls = !_showControls;
            });
            if (_showControls) {
              _startHideControlsTimer();
            }
          },
          onDoubleTap: _toggleFullScreen,
          child: _buildVideoPlayer(),
        ),

        // 控制栏
        if (_showControls) _buildControls(),

        // 顶部按钮栏
        if (_showControls) _buildTopBar(),
      ],
    );
  }

  /// 构建顶部按钮栏
  Widget _buildTopBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top + 12.h,
          left: 16.w,
          right: 16.w,
          bottom: 12.h,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.black.withOpacity(0.7), Colors.transparent],
          ),
        ),
        child: Row(
          children: [
            // 关闭按钮
            GestureDetector(
              onTap: _closeDialog,
              child: Container(
                width: 40.w,
                height: 40.h,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  shape: BoxShape.circle,
                ),
                child: Icon(Icons.close, color: Colors.white, size: 24.sp),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建控制栏
  Widget _buildControls() {
    final bottomPadding =
        _isFullScreen ? MediaQuery.of(context).padding.bottom : 0.0;

    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.only(
          top: 12.h,
          left: 16.w,
          right: 16.w,
          bottom: bottomPadding + 12.h,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
            colors: [Colors.black.withOpacity(0.7), Colors.transparent],
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 进度条
            _buildProgressBar(),
            SizedBox(height: 12.h),
            // 控制按钮栏
            Row(
              children: [
                // 播放/暂停按钮
                GestureDetector(
                  onTap: _togglePlayPause,
                  child: Container(
                    width: 48.w,
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      _isPlaying ? Icons.pause : Icons.play_arrow,
                      color: Colors.white,
                      size: 28.sp,
                    ),
                  ),
                ),
                SizedBox(width: 16.w),
                // 时间显示
                Text(
                  '${_formatDuration(_position)} / ${_formatDuration(_duration)}',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 24.sp,
                  ),
                ),
                const Spacer(),
                // 全屏按钮（右下角）
                GestureDetector(
                  onTap: _toggleFullScreen,
                  child: Container(
                    width: 48.w,
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      _isFullScreen ? Icons.fullscreen_exit : Icons.fullscreen,
                      color: Colors.white,
                      size: 28.sp,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    final progress = _duration.inMilliseconds > 0
        ? _position.inMilliseconds / _duration.inMilliseconds
        : 0.0;

    return LayoutBuilder(
      builder: (context, constraints) {
        return GestureDetector(
          onHorizontalDragStart: (_) {
            setState(() {
              _isDragging = true;
            });
            _hideControlsTimer?.cancel();
          },
          onHorizontalDragUpdate: (details) {
            if (_duration.inMilliseconds > 0) {
              final width = constraints.maxWidth;
              final dx = details.localPosition.dx.clamp(0.0, width);
              final newProgress = (dx / width).clamp(0.0, 1.0);
              final newPosition = Duration(
                milliseconds: (newProgress * _duration.inMilliseconds).round(),
              );
              setState(() {
                _position = newPosition;
              });
            }
          },
          onHorizontalDragEnd: (_) {
            setState(() {
              _isDragging = false;
            });
            _seekTo(_position);
            _startHideControlsTimer();
          },
          onTapDown: (details) {
            if (_duration.inMilliseconds > 0) {
              final width = constraints.maxWidth;
              final dx = details.localPosition.dx.clamp(0.0, width);
              final newProgress = (dx / width).clamp(0.0, 1.0);
              final newPosition = Duration(
                milliseconds: (newProgress * _duration.inMilliseconds).round(),
              );
              _seekTo(newPosition);
            }
          },
          child: Container(
            height: 48.h,
            padding: EdgeInsets.symmetric(vertical: 14.h),
            child: Stack(
              alignment: Alignment.centerLeft,
              children: [
                // 背景进度条
                Container(
                  height: 8.h,
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                ),
                // 已播放进度
                FractionallySizedBox(
                  widthFactor: progress.clamp(0.0, 1.0),
                  alignment: Alignment.centerLeft,
                  child: Container(
                    height: 8.h,
                    decoration: BoxDecoration(
                      color: const Color(0xFF007AFF),
                      borderRadius: BorderRadius.circular(4.r),
                    ),
                  ),
                ),
                // 进度指示点
                Positioned(
                  left: (progress * constraints.maxWidth - 10.w).clamp(
                    0.0,
                    constraints.maxWidth - 20.w,
                  ),
                  child: Container(
                    width: 20.w,
                    height: 20.w,
                    decoration: BoxDecoration(
                      color: const Color(0xFF007AFF),
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 3),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.4),
                          blurRadius: 6,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer() {
    // 如果有错误消息，显示错误
    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, color: Colors.white54, size: 80.w),
            SizedBox(height: 16.h),
            Text(
              '视频加载失败',
              style: TextStyle(color: Colors.white, fontSize: 24.sp),
            ),
            SizedBox(height: 8.h),
            Text(
              _errorMessage!,
              style: TextStyle(color: Colors.white70, fontSize: 20.sp),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      );
    }

    // 如果正在加载，显示加载指示器
    if (_isLoading || _controller == null || !_controller!.value.isInitialized) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Colors.white),
            SizedBox(height: 16.h),
            Text(
              '正在加载视频...',
              style: TextStyle(color: Colors.white, fontSize: 24.sp),
            ),
          ],
        ),
      );
    }

    // 显示视频播放器
    if (_isFullScreen) {
      // 全屏模式：填充整个屏幕（包括安全区）
      final mediaQuery = MediaQuery.of(context);
      return SizedBox(
        width: mediaQuery.size.width,
        height: mediaQuery.size.height,
        child: ClipRRect(
          borderRadius: BorderRadius.zero,
          child: AspectRatio(
            aspectRatio: _controller!.value.aspectRatio,
            child: VideoPlayer(_controller!),
          ),
        ),
      );
    } else {
      // 弹出框模式：按照视频原始尺寸显示，保持宽高比
      return Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16.r),
          child: AspectRatio(
            aspectRatio: _controller!.value.aspectRatio,
            child: VideoPlayer(_controller!),
          ),
        ),
      );
    }
  }
}

